<!-- 部门管理 -->
<template>
    <div class="dept-box">
        <!-- 查询 -->
        <el-form :inline="true" ref="deptRuleFormRef" :model="deptRuleForm" label-width="120px" class="demo-ruleForm"
            :size="formSize" status-icon>
            <el-form-item label="部门名称" prop="deptName">
                <el-input v-model.trim="deptRuleForm.deptName" placeholder="请输入部门名称" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="deptSubmitForm(deptRuleFormRef)">查询</el-button>
                <el-button @click="resetForm(deptRuleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 主体 -->
        <div class="table-but mb-5 mt-5">
            <el-button type="primary" @click="deptCreate" v-has="'dept-add'">创建</el-button>
        </div>
        <!-- 表格数据 -->
        <div class="table-box">
            <el-table :data="tableData" style="width: 100%" row-key="_id"
                :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
                <!-- 表格标题 -->
                <el-table-column :label="item.label" :prop="item.property" v-for="(item, index) in columns" :key="index"
                    :width="item.width" />
                <el-table-column align="center" label="操作" width="200">
                    <template #default="scope">
                        <el-button size="small" @click="handleEdit(scope.row)" v-has="'dept-edit'">编辑</el-button>
                        <el-button size="small" type="danger" @click="handleDelete(scope.row)" v-has="'dept-delete'">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 对话框 -->
            <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%" draggable @close="dialogClose">
                <div>
                    <el-form ref="DialogRuleFormRef" :model="DialogRuleForm" :rules="rules" label-width="120px"
                        class="demo-ruleForm" :size="formSize" status-icon>
                        <el-form-item label="选择部门" prop="deptId">
                            <el-cascader :options="options2" :props="props1" clearable
                                v-model="DialogRuleForm.deptId" />
                            <span>不选则为一级部门</span>
                        </el-form-item>
                        <el-form-item label="公司/部门名称" prop="deptName">
                            <el-input v-model="DialogRuleForm.deptName" placeholder="请输入公司/部门名称" />
                        </el-form-item>
                        <el-form-item label="负责人" prop="userName">
                            <el-select v-model="DialogRuleForm.userName" clearable placeholder="请选择负责人"
                                @change="changeUserName">
                                <el-option v-for="item in options" :key="item._id" :label="item.userName"
                                    :value="item.userName" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="负责人邮箱" prop="userEmail">
                            <el-input v-model="DialogRuleForm.userEmail" placeholder="请选择负责人" disabled />
                        </el-form-item>
                    </el-form>

                </div>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="DialogSubmitForm(DialogRuleFormRef)">确定</el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script setup lang="ts">
import { onActivated,onMounted, nextTick, reactive, ref, computed } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '../../api'


onActivated(() => {
    console.info('缓存组件重新激活')
})
onMounted(() => {
    getdeptlistapi()//获取部门列表
    getuserlistapi()//获取用户列表
})
//获取部门列表
const getdeptlistapi = (obj?: any) => {
    api.getDeptListApi(obj).then((res: any) => {
        console.log(res);
        tableData.value = res
        options2.value = res
    })
}
//获取用户列表
const getuserlistapi = () => {
    api.getUserListApi({ type: 'dept' }).then((res: any) => {
        options.value = res
    })
}


// 头部查询
const formSize = ref('default')//用于控制该表单内组件的尺寸
const deptRuleFormRef = ref<FormInstance>()//获取ref节点
// 查询的数据
const deptRuleForm = reactive({
    deptName: '',
})

//查询按钮
const deptSubmitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            getdeptlistapi(deptRuleForm)//获取部门列表
        } else {
            console.log('error submit!', fields)
        }
    })
}
//重置按钮
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}



// 表格操作按钮(对话框)
const dialogVisible = ref(false)//对话框开关
const active = ref('create')//判断对话框是创建还是编辑
//对话框动态title
const dialogTitle = computed(() => {
    if (active.value == 'create') {
        return '创建'
    }
    if (active.value == 'edit') {
        return '编辑'
    }
})
//获取ref节点
const DialogRuleFormRef = ref<FormInstance>()
// 提交表单数据
const DialogRuleForm: any = reactive({
    deptId: [null],
    deptName: '',
    userName: '',
    userEmail: '',
})
// 对话框表单验证
const rules = reactive({
    deptName: [
        {
            required: true,//是否必填
            message: '请输入部门名称',//提示信息
            trigger: 'blur',//失去焦点时触发验证
        },
        {
            min: 2,
            max: 10,
            message: '部门名称长度在2-10之间',
            trigger: 'blur',
            informType: 'warning',
        },
    ],
    userName: [
        {
            required: true,//是否必填
            message: '请输入负责人名称',//提示信息
            trigger: 'blur',//失去焦点时触发验证
        },
        {
            min: 2,
            max: 10,
            message: '负责人名称长度在2-10之间',
            trigger: 'blur',
            informType: 'warning',
        },
    ],
})
// 父级菜单(级联选择器)
const props1 = {
    checkStrictly: true,
    label: 'deptName',
    value: '_id'
}
// 父级菜单(级联选择器)
const options2: any = ref()
// 下拉选择器(负责人名称列表)
const options = ref()
// 选中负责人时匹配对应的负责人邮箱
const changeUserName = (value: any) => {
    if (value) {//value为选中的值(userName)
        options.value.forEach((item: any) => {
            if (item.userName == value) {
                DialogRuleForm.userEmail = item.userEmail
            }
        })
    } else {
        //不选中时清空邮箱
        DialogRuleForm.userEmail = ''
    }
}
// 确定按钮(创建/编辑)
const DialogSubmitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            let params: any = DialogRuleForm
            //判断是创建还是编辑
            params.active = active.value
            //调用创建/编辑用户接口
            api.getDeptOperateApi(params).then(res => {
                if (res) {
                    //关闭对话框
                    dialogVisible.value = false
                    getdeptlistapi()//获取部门列表
                    ElMessage({
                        message: '创建成功',
                        type: 'success',
                    })
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}
// 对话框关闭回调
const dialogClose = () => {
    //重置表单数据
    resetForm(DialogRuleFormRef.value)
}




//创建部门
const deptCreate = () => {
    active.value = 'create'//创建状态
    dialogVisible.value = true//开启对话框
}




// 主体表格
const tableData: any = ref([])// 表单数据
// 表格标题
const columns = [
    {
        label: '部门名称',
        property: 'deptName',
    },
    {
        label: '负责人',
        property: 'userName',
    },
    {
        label: '负责人邮箱',
        property: 'userEmail',
    },
    {
        label: '更新时间',
        property: 'updateTime',
        width: '220px'
    },
    {
        label: '注册时间',
        property: 'createTime',
        width: '220px'
    }
]
// 单个编辑
const handleEdit = (row: User) => {
    active.value = 'edit'//编辑状态
    nextTick(() => {    //nextTick:在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法，获取更新后的 DOM。(重置表单数据)
        Object.assign(DialogRuleForm, row)//将当前行的数据赋值给表单    Object.assign()合并/覆盖对象    !!!好像有bug
        dialogVisible.value = true//开启对话框
    })
}
// 单个删除
const handleDelete = (row: User) => {
    console.log(row._id);
    ElMessageBox.confirm(
        '您确定要删除吗?',
        '提示',
        {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'warning',
            draggable: true,//属性为true以做到拖拽
        }
    )
        .then(() => {
            // 调用删除菜单接口
            api.getDeptDeleteApi({ _id: row._id })
            getdeptlistapi()//获取部门列表
            ElMessage({
                type: 'success',
                message: '删除成功',
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消删除',
            })
        })
}




</script>

<style scoped lang="less">
.el-select {
    width: 200px;
}

.demo-pagination-block+.demo-pagination-block {
    margin-top: 10px;
}

.demo-pagination-block .demonstration {
    margin-bottom: 16px;
}
</style>